package com.redis.common.component.listener;

import cn.hutool.core.collection.CollUtil;
import com.redis.common.component.handler.AuthenticationFailureHandler;
import com.redis.common.service.SecurityUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.security.authentication.event.AuthenticationFailureBadCredentialsEvent;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @description: 认证失败事件监听器
 * @Author C_Y_J
 * @create 2022/1/13 16:36
 **/
public class AuthenticationFailureEventListener implements ApplicationListener<AuthenticationFailureBadCredentialsEvent> {

    @Autowired(required = false)
    private AuthenticationFailureHandler failureHandler;

    /**
     * Handle an application event.
     *
     * @param event the event to respond to
     */
    @Override
    public void onApplicationEvent(AuthenticationFailureBadCredentialsEvent event) {


        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();

        HttpServletRequest request = requestAttributes.getRequest();
        HttpServletResponse response = requestAttributes.getResponse();

        AuthenticationException authenticationException = event.getException();
        Authentication authentication = (Authentication) event.getSource();

        // 调用自定义业务实现
        if (failureHandler != null) {
            failureHandler.handle(authenticationException, authentication, request, response);
        }
    }

    private boolean isUserAuthentication(Authentication authentication) {
        if (authentication.getPrincipal() instanceof SecurityUser) {
            return true;
        }
        return CollUtil.isNotEmpty(authentication.getAuthorities());
    }

}